<template>
  <div class="game-container">
    <!-- 返回按钮 -->
    <button class="back-button" @click="$router.push('/game')">
      <svg width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
        <polyline points="15 18 9 12 15 6"></polyline>
      </svg>
    </button>

    <!-- 新的容器，用于放置canvas和其上方的元素 -->
    <div class="game-content">
      <!-- 上方信息容器 -->
      <div class="top-info-container">
        <!-- 得分显示区域 -->
        <div class="score-container">
          <div class="score">
            <h3>得分</h3>
            <p>{{ score }}</p>
          </div>
          <div class="best-score">
            <h3>最高分</h3>
            <p>{{ bestScore }}</p>
          </div>
        </div>

        <!-- 下一个方块显示区域 -->
        <div class="next-piece-container">
          <h3>下一个</h3>
          <canvas ref="nextPieceCanvas" class="next-piece-canvas"></canvas>
        </div>
      </div>

      <canvas id="tetrisCanvas" class="game-canvas"></canvas>
    </div>

    <!-- 操作提示 -->
    <div class="operation-guide">
      <h3>游戏操作</h3>
      <ul>
        <li>← →键: 左右移动方块</li>
        <li>↑键: 旋转方块</li>
        <li>↓键: 加速下降</li>
        <li>空格键: 瞬间下落</li>
        <li>P键: 暂停/继续游戏</li>
        <li>R键: 重新开始游戏</li>
      </ul>
    </div>

    <!-- 开始游戏提示遮罩层 -->
    <div class="start-overlay" v-if="showStartOverlay">
      <div class="start-content">
        <h2>俄罗斯方块</h2>
        <p>按 R 键开始游戏</p>
      </div>
    </div>

    <!-- 暂停遮罩层 -->
    <div class="pause-overlay" v-if="isPaused && !gameOver">
      <div class="pause-content">
        <h2>游戏暂停</h2>
        <p>按 P 键继续游戏</p>
      </div>
    </div>

    <!-- 游戏结束遮罩层 -->
    <div class="game-over-overlay" v-if="gameOver">
      <div class="game-over-content">
        <h2>游戏结束</h2>
        <p>最终得分: {{ score }}</p>
        <p>按 R 键重新开始</p>
      </div>
    </div>
  </div>
</template>
<script>
import tetrisGame from '@/utils/tetrisCanvas.js';

export default {
  name: 'TetrisGame',
  data() {
    return {
      isPaused: false,
      gameOver: false,
      score: 0,
      bestScore: 0,
      nextPiece: null,
      showStartOverlay: true  // 添加这个属性来控制开始提示遮罩层的显示
    };
  },
  mounted() {
    // 初始化游戏但不开始
    tetrisGame.initGame();
    
    // 监听游戏状态变化
    this.setupGameStateListener();
    
    // 初始化下一个方块显示
    this.initNextPieceDisplay();
    
    // 初始化最高分
    this.initBestScore();
    
    // 添加键盘事件监听器
    this.addStartKeyListener();
  },
  beforeUnmount() {
    // 清理状态监听器
    if (this.gameStateInterval) {
      clearInterval(this.gameStateInterval);
    }
    
    // 移除键盘事件监听器
    window.removeEventListener('keydown', this.handleStartKey);
    
    // 重置游戏状态
    tetrisGame.resetGame();
    
    // 清理游戏
    tetrisGame.cleanup();
  },
  methods: {
    // 添加开始游戏的键盘监听器
    addStartKeyListener() {
      window.addEventListener('keydown', this.handleStartKey);
    },
    
    // 处理开始游戏的按键
   handleStartKey(event) {
      if (event.key === 'r' || event.key === 'R') {
        // 隐藏开始提示遮罩层
        this.showStartOverlay = false;
        
        // 开始游戏
        tetrisGame.startGame();
        
        // 更新下一个方块显示
        this.updateNextPiece();
        
        // 移除事件监听器，避免重复触发
        window.removeEventListener('keydown', this.handleStartKey);
      }
    },
    
    setupGameStateListener() {
      // 监听游戏状态变化
      const updateGameState = () => {
        this.isPaused = tetrisGame.isPaused;
        this.gameOver = tetrisGame.gameState.gameOver;
        this.score = tetrisGame.score;
        
        // 更新最高分
        this.updateBestScore();
        
        // 更新下一个方块
        this.updateNextPiece();
      };
      
      // 定期更新游戏状态
      this.gameStateInterval = setInterval(updateGameState, 100);
    },
    
    // 初始化最高分
   initBestScore() {
      const savedBestScore = sessionStorage.getItem('tetrisBestScore');
      if (savedBestScore) {
        this.bestScore = parseInt(savedBestScore, 10);
      }
    },
    
    // 更新最高分
    updateBestScore() {
      if (this.score > this.bestScore) {
        this.bestScore = this.score;
        // 保存到sessionStorage
        sessionStorage.setItem('tetrisBestScore', this.bestScore.toString());
      }
    },
    
    // 修改 initNextPieceDisplay 方法
    initNextPieceDisplay() {
      // 初始化下一个方块显示
      this.nextPieceCanvas = this.$refs.nextPieceCanvas;
      this.nextPieceCtx = this.nextPieceCanvas.getContext('2d');
      
      // 设置画布大小
      this.nextPieceCanvas.width = 120;
      this.nextPieceCanvas.height = 120;
    },
    
    updateNextPiece() {
      // 只有在游戏开始后才更新下一个方块显示
      if (tetrisGame.gameState.gameStarted || tetrisGame.gameState.gameOver) {
        // 获取下一个方块
        this.nextPiece = tetrisGame.getNextPiece();
        
        // 绘制下一个方块
        this.drawNextPiece();
      }
    },
    
    drawNextPiece() {
      if (!this.nextPieceCtx || !this.nextPiece) return;
      
      // 清空画布
      this.nextPieceCtx.clearRect(0, 0, this.nextPieceCanvas.width, this.nextPieceCanvas.height);
      
      // 设置方块大小
      const cellSize = 20;
      
      // 居中绘制方块
      const offsetX = (this.nextPieceCanvas.width - this.nextPiece[0].length * cellSize) / 2;
      const offsetY = (this.nextPieceCanvas.height - this.nextPiece.length * cellSize) / 2;
      
      // 绘制方块
      for (let y = 0; y < this.nextPiece.length; y++) {
        for (let x = 0; x < this.nextPiece[y].length; x++) {
          if (this.nextPiece[y][x]) {
            // 使用tetrisGame中的颜色
            this.nextPieceCtx.fillStyle = tetrisGame.colors[this.nextPiece[y][x]];
            this.nextPieceCtx.fillRect(
              offsetX + x * cellSize,
              offsetY + y * cellSize,
              cellSize, cellSize
            );
            
            // 绘制边框
            this.nextPieceCtx.strokeStyle = 'white';
            this.nextPieceCtx.strokeRect(
              offsetX + x * cellSize,
              offsetY + y * cellSize,
              cellSize, cellSize
            );
          }
        }
      }
    }
  }
};
</script>
<style scoped>
.game-container {
  width: 100%;
  height: 100vh;
  display: flex;
  justify-content: center;
  align-items: center;
  background-color: #6d6b6b;
  position: relative;
  overflow: hidden;
}

/* 添加响应式背景 */
@media (max-width: 768px) {
  .game-container {
    background-color: #272626;
  }
}

.game-content {
  display: flex;
  flex-direction: column;
  align-items: center;
  position: relative;
}

/* 上方信息容器 */
.top-info-container {
  display: flex;
  justify-content: space-between;
  align-items: flex-start;
  width: 100%;
  margin-bottom: 10px;
}

.back-button {
  position: absolute;
  top: 20px;
  left: 20px;
  background: rgba(0, 0, 0, 0.5);
  color: white;
  border: none;
  border-radius: 5px;
  padding: 10px 15px;
  display: flex;
  align-items: center;
  gap: 5px;
  cursor: pointer;
  z-index: 100;
  transition: all 0.3s ease;
}

.back-button:hover {
  background: rgba(0, 0, 0, 0.8);
  transform: scale(1.05);
}

/* 得分显示区域样式 */
.score-container {
  display: flex;
  flex-direction: row; /* 改为横向排列 */
  gap: 30px; /* 增加间距 */
  background: rgba(0, 0, 0, 0.7);
  color: white;
  padding: 15px 30px;
  border-radius: 10px;
  text-align: center;
  z-index: 100;
}

.score-container .score,
.score-container .best-score {
  display: flex;
  flex-direction: column;
  align-items: center;
}

.score-container h3 {
  margin: 0;
  font-size: 16px;
  border-bottom: 1px solid rgba(255, 255, 255, 0.3);
  padding-bottom: 5px;
}

.score-container p {
  margin: 5px 0 0 0;
  font-size: 24px;
  font-weight: bold;
}

.next-piece-container {
  background: rgba(0, 0, 0, 0.7);
  color: white;
  padding: 15px;
  border-radius: 10px;
  width: 150px;
  text-align: center;
  z-index: 100;
  /* 在PC端将下一个方块放在canvas右边 */
  position: absolute;
  top: 0;
  right: -170px;
}

.next-piece-container h3 {
  margin-top: 0;
  margin-bottom: 10px;
  font-size: 16px;
  border-bottom: 1px solid rgba(255, 255, 255, 0.3);
  padding-bottom: 5px;
}

.next-piece-canvas {
  width: 120px;
  height: 120px;
  background-color: #272626;
}

.operation-guide {
  position: absolute;
  bottom: 20px;
  right: 20px;
  background: rgba(0, 0, 0, 0.7);
  color: white;
  padding: 15px;
  border-radius: 10px;
  max-width: 200px;
  z-index: 100;
}

/* 在移动端隐藏操作提示 */
@media (max-width: 768px) {
  .operation-guide {
    display: none;
  }
  
  /* 在移动端将下一个方块放在得分右边 */
  .next-piece-container {
    position: relative;
    top: auto;
    right: auto;
    margin-top: 0;
    width: auto;
  }
}

.operation-guide h3 {
  margin-top: 0;
  margin-bottom: 10px;
  font-size: 16px;
  border-bottom: 1px solid rgba(255, 255, 255, 0.3);
  padding-bottom: 5px;
}

.operation-guide ul {
  list-style-type: none;
  padding: 0;
  margin: 0;
}

.operation-guide li {
  margin-bottom: 8px;
  font-size: 14px;
  display: flex;
  align-items: center;
  gap: 5px;
}

.game-canvas {
  width: 600px;
  height: 600px;
  position: relative;
}

/* 添加Canvas的响应式支持 */
@media (max-width: 768px) {
  .game-canvas {
    width: 90vw;
    height: 90vw;
    max-width: 400px;
    max-height: 400px;
  }
  
  /* 在移动端调整布局 */
  .top-info-container {
    justify-content: space-around;
  }
  
  .next-piece-canvas {
    width: 80px;
    height: 80px;
  }
  
  .score-container {
    margin-right: 20px;
  }
}

.pause-overlay, .game-over-overlay, .start-overlay {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  background-color: rgba(0, 0, 0, 0.7);
  display: flex;
  justify-content: center;
  align-items: center;
  z-index: 200;
}

.pause-content, .game-over-content, .start-content {
  text-align: center;
  color: white;
}

.pause-content h2, .game-over-content h2, .start-content h2 {
  font-size: 36px;
  margin-bottom: 15px;
}

.pause-content p, .game-over-content p, .start-content p {
  font-size: 18px;
  opacity: 0.8;
}

/* 在移动端调整暂停/结束遮罩层的字体大小 */
@media (max-width: 768px) {
  .pause-content h2, .game-over-content h2, .start-content h2 {
    font-size: 28px;
  }
  
  .pause-content p, .game-over-content p, .start-content p {
    font-size: 16px;
  }
}
</style>